<template>
  <div class="tem-container" id="markdownEditor">
    <div class="tem-botton">
      <el-button type="primary" size="mini" @click="goBack">返回</el-button>
      <el-button type="primary" size="mini" @click="openSubmitDialog">提交</el-button>
    </div>
    <div class="tem-testarea">
      <mavon-editor
        class="tem-markdown"
        v-model="context"
        :toolbars="toolbars"
        @change="change"
        ref="md"
        @imgAdd="$imgAdd" @imgDel="$imgDel"
      />
    </div>
    <div class="dialog-submit-content">
      <el-dialog
        title="提交"
        :visible.sync="submitDialogVisible"
        width="30%"
        center>
        <el-form :model="contentForm" :rules="rules" ref="contentForm" label-width="100px" label-position="top">
          <el-form-item label="主题" prop="title">
            <el-input v-model="contentForm.title"></el-input>
          </el-form-item>
          <el-form-item label="标记" prop="region">
            <el-select v-model="contentForm.region" placeholder="请选择活动区域">
              <el-option label="标记一" value="shanghai"></el-option>
              <el-option label="标记二" value="beijing"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传附件" prop="file">
            <el-upload
              class="upload-demo"
              drag
              action="https://jsonplaceholder.typicode.com/posts/"
              multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <!-- <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('contentForm')">确定</el-button>
            <el-button @click="resetForm('contentForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import api from "../api"
export default {
  data() {
    return {
      context: "", //输入的数据
      saveContext: "", //输入的数据
      imgFile: [],
      toolbars: {
        bold: true, // 粗体
        italic: true, // 斜体
        header: true, // 标题
        underline: true, // 下划线
        mark: true, // 标记
        superscript: true, // 上角标
        quote: true, // 引用
        ol: true, // 有序列表
        link: true, // 链接
        imagelink: true, // 图片链接
        help: true, // 帮助
        code: true, // code
        subfield: true, // 是否需要分栏
        fullscreen: true, // 全屏编辑
        readmodel: true, // 沉浸式阅读
        /* 1.3.5 */
        undo: true, // 上一步
        trash: true, // 清空
        ishljs: true,
        save: true, // 保存（触发events中的save事件）
        /* 1.4.2 */
        navigation: true // 导航目录
      },
      submitDialogVisible: false,
      contentForm: {
        title: '',
        sign: '',
        type: [],
        file: '',
        saveContext: "",
        saveContextHtml: ""
      },
      rules: {
        title: [
          { required: true, message: '请输入主题名称', trigger: 'blur' },
          { min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur' }
        ],
        sign: [
          { required: true, message: '请选择标记', trigger: 'change' }
        ],
        type: [
          { type: 'array', required: true, message: '请至少选择一个活动性质', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    goBack() {
      this.$router.go(-1)
    },
    // 所有操作都会被解析重新渲染
    change(value, render) {
      // render 为 markdown 解析后的结果[html]
      this.contentForm.saveContextHtml = render
      console.log(this.$refs.md)
    },
    // 绑定@imgAdd event
    $imgAdd(pos, $file) {
      this.imgFile[pos] = $file
    },
    deepClone (obj) {
      // Handle the 3 simple types, and null or undefined
      if (null == obj || "object" != typeof obj) return obj
      // Handle Date
      if (obj instanceof Date) {
        var copy = new Date()
        copy.setTime(obj.getTime())
        return copy
      }
      // Handle Array
      if (obj instanceof Array) {
        var copy = []
        for (var i = 0, len = obj.length; i < len; i++) {
            copy[i] = clone(obj[i])
        }
        return copy
      }
      // Handle Object
      if (obj instanceof Object) {
        var copy = {}
        for (var attr in obj) {
          if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr])
        }
        return copy
      }
      throw new Error("Unable to copy obj! Its type isn't supported.")
    },
    replaceImgUrls (imgFiles, urls) {
      for (var i = 1; i <= imgFiles.length; i++) {
        if (imgFiles[i] === undefined) {
          continue
        }
        let name = imgFiles[i].name
        if (name.includes('-')) {
          name = name.replace(/-/g, '')
        }
        let url = urls[name]
        let pos = i
        let content = this.contentForm.saveContext
        if (content.includes(name)) {
          let oStr = `(${pos})`
          let nStr = `(${url})`
          let index = content.indexOf(oStr)
          let str = content.replace(oStr, '')
          let insertStr = (soure, start, newStr) => {
            return soure.slice(0, start) + newStr + soure.slice(start)
          }
          this.contentForm.saveContext = insertStr(str, index, nStr)
        }
      }
      console.log(1111)
      this.saveContent()
    },
    isExistImg (pos, $file) {
      let name = $file.name
      if (name.includes('-')) {
        name = name.replace(/-/g, '')
      }
      name = `![${name}]`
      let index = `(${pos})`
      let insertStr = (soure, newStr) => {
        return soure + newStr
      }
      name = insertStr(name, index)
      let content = this.context
      if (content.includes(name)) {
        return true
      } else {
        delete this.imgFile[pos]
        return false
      }
    },
    $imgDel (pos) {
      delete this.imgFile[pos]
    },
    uploadimg () {
      var this_ = this
      // 第一步.将图片上传到服务器.
      var formdata = new FormData()
      var isSameImgs = []
      for(var _img in this.imgFile){
        if (this.isExistImg(_img, this.imgFile[_img]) && isSameImgs.indexOf(this.imgFile[_img].name) === -1) {
          isSameImgs.push(this.imgFile[_img].name)
          formdata.append('image', this.imgFile[_img])
        } else {
          continue
        }
      }
      api.postImg("/menu/saveMultipleImg", formdata)
        .then(res => {
          this_.replaceImgUrls(this_.imgFile, res.data)
        }).catch(err => {})
    },
    saveContent () {
      api.post('/menu/saveContent', {
        contentForm: JSON.stringify(this.contentForm)
      }).then(res => {
        if (res.data.code === '0000') {
          this.submitDialogVisible = false
          this.goBack()
        }
      }).catch(err => {})
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.imgFile.length > 0) {
            this.uploadimg()
          } else {
            this.saveContent()
          }
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    openSubmitDialog () {
      if (this.context.trim().length > 0) {
        this.submitDialogVisible = true
        this.contentForm.saveContext = this.deepClone(this.context)
      } else {
        this.$message({message: '警告哦，这是一条警告消息', type: 'warning'})
      }
    },
    getContent () {
      api.post('/menu/getContent', {
      }).then(res => {
        this.context = res.data.data
      }).catch(err => {})
    }
  },
  mounted () {
    this.getContent()
  }
}
</script>
<style scoped>
.tem-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.tem-botton {
  display: flex;
  justify-content: space-between;
  padding: 10px 10px 2px 10px;
}
.tem-testarea {
  width: calc(100% - 20px);
  height: calc(100% - 60px);
  background: #fff;
  box-shadow: 0 0 5px #ccc;
  margin: 8px;
}
.tem-markdown {
  height: 100%;
  overflow: auto;
}
.tem-submit-title {
  display: inline-block;
  padding: 10px;
  font-size: 14px;
}
</style>
<style src="../res/css/markdownEditor.css"></style>